package com.yricky.indesk.utils

import com.yricky.indesk.model.pojo.AppEntrance
import com.yricky.indesk.model.pojo.DesktopConfig

/**
 * @author Yricky
 * @date 2021/12/26
 */

fun DesktopConfig.resize(row:Int,col:Int):DesktopConfig = DesktopConfig(
    row,col,
    pages.flatten().chunked(row * col)
)

fun DesktopConfig.removeInvalidItem():DesktopConfig = DesktopConfig(
    row, column,
    pages.map { it.filter { entrance -> entrance.isValid() || entrance.isEmpty() } }
        .filterIndexed{ pIndex,it-> pIndex==0 || it.isNotEmpty() }
)

fun DesktopConfig.removeItem(pageIndex:Int,index:Int):DesktopConfig = DesktopConfig(
    row, column,
    pages.mapIndexed { pIndex,it->
            if(pIndex == pageIndex)
                it.filterIndexed { eIndex,_ -> eIndex != index }
            else it
        }
        .filterIndexed{ pIndex,it-> pIndex==0 || it.isNotEmpty() }
)

fun DesktopConfig.isFull():Boolean = pages.all {
    it.size == column*row
}

fun DesktopConfig.addEntrance(entrance: List<AppEntrance>) = DesktopConfig(
    row, column,
    if(isFull()){
        pages.plus(listOf(entrance))
    }else{
        val index = pages.indexOfFirst { it.size < column*row }
        pages.flatMapIndexed { i,it->
            if(i == index){
                it.plus(entrance).chunked(row*column)
            }else listOf(it)
        }
    }
)